# -*- coding:utf8 -*-
# !/usr/bin/python
'''
author: ning.luo
createTime: 2021/9/6 18:04
update: ning.luo
updateTime: 2021/9/6 18:04
description: 更新微信用户id
'''
import datetime
import os
import requests
import pymysql
from logging import getLogger

info_log = getLogger("info")
error_log = getLogger("error")

pwd = os.path.dirname(os.path.abspath(__file__))

class MysqlHelper:
    """
    电商平台四种环境的数据库连接
    """

    def __init__(self, db, env):

        # self.env = TD.get_global_data('env')
        self.connect = None
        self.cursor = None
        self.tunnel = None
        self.env =env
        self._connect(db)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_trackback):
        self.close()
        if exc_trackback is None:
            exit_result = True
        else:
            exit_result = False
        return exit_result

    def _connect(self, db):
        if self.env == "dev":
            self.connect = pymysql.Connect(
                host='10.118.71.152',
                port=3306,
                user='root',
                passwd='mH1FF!WJemh&',
                db=db,
                charset='utf8'
            )
        elif self.env == "ci":
            self.connect = pymysql.Connect(
                host='10.7.0.41',
                port=3306,
                user='root',
                passwd='mH1FF!WJemh&',
                db=db,
                charset='utf8'
            )
        else:
            self.connect = pymysql.Connect(
                host='10.7.0.81',
                port=3306,
                user='murphy',
                passwd='hkoe;dlh&dsfVF5zv',
                db=db,
                charset='utf8'
            )
        self.cursor = self.connect.cursor(cursor=pymysql.cursors.DictCursor)

    def sql_execute(self, sql):
        """
        功能：连接数据库，执行sql语句
        入参：sql语句 string类型
        返回值：sql语句执行结果 list类型
        调用说明：1. 先实例化类 2. 再直接调用本方法 3. 关闭连接
        """

        self.cursor.execute(sql)
        self.connect.commit()  # 提交sql语句
        data_list = self.cursor.fetchall()
        # info_log.info('sql执行结果：{}'.format(data_list))  # 打印sql执行结果
        print("执行结果：", data_list)
        return data_list

    def close(self):
        self.cursor.close()
        self.connect.close()

class updateWechatUserId:

    def __init__(self):
        self.headers = {'Content-Type': 'application/json;charset=utf-8'}

    def get_access_token(self):
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            "corpid": "wx34b4ed8f75c6657a",
            "corpsecret": "r9gH9QpAmwAtzZCw--vWwSBIuDp6Y7WzmSPxArP3iUk"
        }
        res = requests.get(url, params=params, headers=self.headers)
        access_token = res.json().get("access_token", "")
        return access_token

    def get_department_list(self, access_token):
        url = "https://qyapi.weixin.qq.com/cgi-bin/department/list"
        params = {
            "access_token": access_token,
            "id":5
        }
        res = requests.get(url, params=params, headers=self.headers)
        print(res.json())
        return res.json()["department"]

    def get_department_user(self, access_token, department_id):
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist"
        params = {
            "access_token": access_token,
            "department_id": department_id,
            "fetch_child": 1
        }
        res = requests.get(url, params=params, headers=self.headers)
        return res.json()["userlist"]

    def get_department_user_detail(self, access_token, department_id):
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/list"
        params = {
            "access_token": access_token,
            "department_id": department_id,
            "fetch_child": 1
        }
        res = requests.get(url, params=params, headers=self.headers)
        return res.json()["userlist"]

    def update_user_id(self, user_list):
        with MysqlHelper('ct_test', 'dev') as mysqlHelper:
            for user in user_list:
                query_sql = "SELECT username,name,mobile,email,ding_user_id FROM rbac_userprofile WHERE username='{}'"
                update_sql = "UPDATE rbac_userprofile SET ding_user_id='{}',email='{}' WHERE username='{}'"
                # update_sql = "UPDATE rbac_userprofile SET email='{}' WHERE username='{}' AND email=''"
                insert_sql = "INSERT INTO rbac_userprofile(username,name,mobile,email,ding_user_id,password,is_superuser,first_name,last_name,is_staff,is_active,date_joined) VALUES('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')"
                wechat_user_id = user["userid"]
                staff_id = ""
                for attr in user["extattr"]["attrs"]:
                    if attr["name"] == "工号":
                        staff_id = attr["value"]
                name = user["name"]
                mobile = user["mobile"]
                email = user["email"]
                query_sql = query_sql.format(staff_id)
                user_info = mysqlHelper.sql_execute(query_sql)
                try:
                    if len(user_info)>0:
                        # sql = update_sql.format(wechat_user_id, staff_id)
                        sql = update_sql.format(wechat_user_id, email, staff_id)
                        mysqlHelper.sql_execute(sql)
                    else:
                        sql = insert_sql.format(staff_id,name,mobile,email,wechat_user_id,"",0,"","",0,1,datetime.datetime.now())
                        mysqlHelper.sql_execute(sql)
                except Exception as e:
                    print("更新失败:", str(e))
                    print("执行sql：", sql)


    def main_run(self):
        access_token = aaa.get_access_token()
        user_list = aaa.get_department_user_detail(access_token, 1)
        aaa.update_user_id(user_list)


if __name__ == "__main__":
    aaa = updateWechatUserId()
    aaa.main_run()